package com.jwaoo.mobile.view.contacts;

import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.support.constraint.solver.Goal;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.dx.as.common.JWResult;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jwaoo.chat.ChatHelpter;
import com.jwaoo.mobile.R;
import com.jwaoo.mobile.http.HttpHelper;
import com.jwaoo.mobile.view.account.AccountBean;

import org.json.JSONObject;

import java.util.List;

import http.IHttpListener;

/**
 * A fragment representing a list of Items.
 * <p/>
 * Activities containing this fragment MUST implement the {@link OnListFragmentInteractionListener}
 * interface.
 */
public class ContactsFragment extends Fragment {

    // TODO: Customize parameter argument names
    private static final String ARG_COLUMN_COUNT = "column-count";
    // TODO: Customize parameters
    private int mColumnCount = 1;

    private RecyclerView recyclerView;
    /**
     * Mandatory empty constructor for the fragment manager to instantiate the
     * fragment (e.g. upon screen orientation changes).
     */
    public ContactsFragment() {
    }

    // TODO: Customize parameter initialization
    @SuppressWarnings("unused")
    public static ContactsFragment newInstance(int columnCount) {
        ContactsFragment fragment = new ContactsFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_COLUMN_COUNT, columnCount);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getArguments() != null) {
            mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_contacts_list, container, false);

        // Set the adapter
        if (view instanceof RecyclerView) {
            Context context = view.getContext();
            recyclerView = (RecyclerView) view;

            if (mColumnCount <= 1) {
                recyclerView.setLayoutManager(new LinearLayoutManager(context));
            } else {
                recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
            }
            Gson gson = new Gson();
            JWResult<List<AccountBean>> result = gson.fromJson(json,new TypeToken<JWResult<List<AccountBean>>>(){}.getType());
            List<AccountBean> list = result.getRst();
            recyclerView.setAdapter(new ContactsRecyclerViewAdapter(list, mListener));
        }
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
//        getData();
    }

    private void getData(){
        HttpHelper.getAccountInfoList(new IHttpListener() {
            @Override
            protected void getData(Object... objects) {

            }

            @Override
            protected void onResponse(Object response, int flg) {
                if (response != null){
                    try {
                        final List<AccountBean> list = (List<AccountBean>) response;
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                recyclerView.setAdapter(new ContactsRecyclerViewAdapter(list, mListener));
                            }
                        });

                    }catch (Exception ex){
                        ex.printStackTrace();
                    }

                }
            }

            @Override
            protected void onFailure(Throwable t) {

            }
        });
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
//        if (context instanceof OnListFragmentInteractionListener) {
//            mListener = (OnListFragmentInteractionListener) context;
//        } else {
//            throw new RuntimeException(context.toString()
//                    + " must implement OnListFragmentInteractionListener");
//        }
    }
    String json = "{\"code\":1000,\"msg\":\"success\",\"rst\":[{\"area\":\"\",\"email\":\"jerry2lin@gmail.com\",\"gender\":\"0\",\"id\":10001,\"level\":\"0\",\"nickname\":\"测试\",\"phone\":\"\",\"uuid\":\"d723a03f46824d9a81faee8bf239608d\"},{\"area\":\"\",\"email\":\"jerry.lin@jwaoo.com\",\"gender\":\"1\",\"id\":10010,\"level\":\"0\",\"nickname\":\"Jerry9527\",\"phone\":\"\",\"uuid\":\"349475e208fd4c1388ea34635e533543\"},{\"area\":\"\",\"email\":\"mark.ma@jwaoo.com\",\"gender\":\"0\",\"id\":10011,\"level\":\"0\",\"nickname\":\"mark.ma@jwaoo.com\",\"phone\":\"\",\"uuid\":\"55e86c2d9e004eb3ae314ee94ead7460\"},{\"area\":\"\",\"email\":\"xiang.dong@jwaoo.com\",\"gender\":\"0\",\"id\":10012,\"level\":\"0\",\"nickname\":\"xiang.dong@jwaoo.com\",\"phone\":\"\",\"uuid\":\"26933d61b0b342e2b8446f0a79b13ee6\"}]}";

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnListFragmentInteractionListener {
        // TODO: Update argument type and name
        void onListFragmentInteraction(AccountBean item);
    }
    private OnListFragmentInteractionListener mListener = new OnListFragmentInteractionListener() {
        @Override
        public void onListFragmentInteraction(AccountBean item) {
            ChatHelpter.startP2PSession(getActivity(),item.getId());
        }
    };
}
